package com.ye.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        获取请求对象
        ServerHttpRequest request = exchange.getRequest();
//        获取响应对象
        ServerHttpResponse response = exchange.getResponse();
//        获取请求头
        HttpHeaders headers = request.getHeaders();


        HttpMethod method = request.getMethod();
        System.out.println("method: "+method);

//        判断当前请求地址是否为登录，如果是，直接放行
        if (request.getURI().getPath().contains("/login")) {
            System.out.println("登录放行");
            return chain.filter(exchange);
        }
//        判断当前请求是否为注册，如果是，自动设置一个临时token
        if (request.getURI().getPath().contains("/register")) {
            System.out.println("注册放行");
            try {
                request.mutate().headers(httpHeaders -> {httpHeaders.set("token","123456");}).build();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(headers.containsKey("token"));
        }


//        判断请求头中是否包含token这个键
        boolean haveToken = headers.containsKey("token");
//        包含，允许通过全局过滤器
        if (haveToken){
            return chain.filter(exchange);
        }
//        否则返回空,前端提醒未通过验证访问
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();

    }

    @Override
    public int getOrder() {
        return 1;
    }

}
